package com.sunseen.capacitormachine.commumication.tcp;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import com.sunseen.capacitormachine.commumication.tcp.event.ChangeDetectStateEvent;
import com.sunseen.capacitormachine.commumication.tcp.event.SendOvenParamEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * 与以太网通信的服务,上位机作为服务端来等待客户端连接
 *
 * @author zest
 */
public class TcpService extends Service {

    private static final String TAG = TcpService.class.getSimpleName();
    private static final int port1 = 20001;
    private static final int port2 = 20005;

    private InfraredDataServer server20001;
    private InfraredDataServer server20005;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "TcpService onCreate");
        EventBus.getDefault().register(this);
        server20001 = new InfraredDataServer(port1, 0);
        server20005 = new InfraredDataServer(port2, 1);
        server20001.start();
        server20005.start();
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onDetectStateChange(ChangeDetectStateEvent event) {
        if (event.isStart()) {
            Log.e(TAG, "开启数据采集");
        } else {
            Log.e(TAG, "暂停数据采集");
        }
        server20001.sendCmd(event.isStart());
        server20005.sendCmd(event.isStart());
    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onSendParam(SendOvenParamEvent event) {
        server20001.sendParams(event.getImplosionTime(),
                event.getImplosionCurrentHighLimit(),
                event.getImplosionCurrentLowLimit(),
                event.getImplosionVoltageHighLimit(),
                event.getImplosionVoltageLowLimit());
        server20005.sendParams(event.getImplosionTime(),
                event.getImplosionCurrentHighLimit(),
                event.getImplosionCurrentLowLimit(),
                event.getImplosionVoltageHighLimit(),
                event.getImplosionVoltageLowLimit());
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        server20001.stop();
        server20005.stop();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

}
